
import router from '../router/index.js'
const programmeFlag = '/call-center/'

/*
 *序列化query
 */
export const serialize = data => {
  const list = []
  Object.keys(data).forEach(ele => {
    list.push(`${ele}=${data[ele]}`)
  })
  return list.join('&')
}
/**
*打开新页面，本地开路由，线上开页签
* @param {(string)} path:路径
* @param {(Object)} query:参数
* @param {(string)} pageName:页签名称
* @param {(string)} menuCode:菜单编码
*/
export function openPage(path, query, pageName, menuCode) {
  if (process.env.NODE_ENV === 'development') {
    router.push({
      path: path,
      query
    })
  } else {
    window.parent.postMessage({
      flag: 'addtag',
      extraData: {
        url: programmeFlag + path.substring(1),
        title: pageName,
        query: query ? '&' + serialize(query) : '',
        menuCode: menuCode
      }
    }, '*')
  }
}
/**
 * 关闭标签
 * @param {*} fullPath
 */
export function closeTag(path) {
  const divs = window.top.document.querySelectorAll('div')
  let tagsView
  for (const d of divs) {
    if (d.__vue__ && d.__vue__.$store && d.__vue__.$store.state.tagsView) {
      tagsView = d.__vue__.$store.state.tagsView
      break
    }
  }
  if (!tagsView) return
  const pathReg = /\/myiframe\/urlPath\?src=(.+)/
  path = window.encodeURIComponent(path)
  let fullPath
  for (const tag of tagsView.visitedViews) {
    if (tag.fullPath && tag.fullPath.includes(path)) {
      fullPath = tag.fullPath.replace(pathReg, '$1')
    }
  }
  if (!fullPath) {
    return
  }
  window.top.postMessage({
    flag: 'closetag',
    extraData: {
      fullPath
    }
  }, '*')
}
